/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.support;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 *
 * @author haolw
 * @time 2017/07/20
 */
public class SimpleStringCache {
	private static Map<String, String> cache = new ConcurrentHashMap<String, String>(16);
	private static final Long DEFAULT_SECOND = -1L;
	private static final String TOKEN = "~";

	/**
	 * 放入数据
	 * 
	 * @param key
	 * @param value
	 */
	public static void put(String key, String value) {
		put(key, value, DEFAULT_SECOND.intValue());
	}

	/**
	 * 放入数据，在second秒后拿该数据，则为null
	 * 
	 * @param key
	 * @param value
	 * @param second
	 */
	public static void put(String key, String value, Integer second) {
		Long now = System.currentTimeMillis();
		Long delayTime = Long.valueOf(second.toString());
		if (!DEFAULT_SECOND.equals(delayTime)) {
			delayTime += now;
		}
		String _value = value + TOKEN + delayTime;
		cache.put(key, _value);
	}

	/**
	 * 拿取数据
	 * 
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		String fromKey = cache.get(key);
		if (fromKey == null || fromKey.length() == 0) {
			return null;
		}
		String[] keys = fromKey.split(TOKEN);
		Long now = System.currentTimeMillis();
		Long delayTime = Long.parseLong(keys[1]);
		if (now >= delayTime && !DEFAULT_SECOND.equals(delayTime)) {
			cache.remove(key);
			return null;
		} else {
			return keys[0];
		}
	}

	/**
	 * 移除某数据
	 * 
	 * @param key
	 */
	public static void remove(String key) {
		cache.remove(key);
	}

	/**
	 * 清空缓存
	 */
	public static void clear() {
		cache.clear();
	}
}
